package com.app.couponsharelife.ui.main.home.search

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import com.google.gson.Gson
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.SearchHistoryBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.databinding.ActivitySearchBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.HistoryRecordListAdapter
import com.app.couponsharelife.ui.adapter.HomeTypeGoodAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.viewmodel.HomeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.AppUtils.hideInputBoard
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_search.*
import java.util.*

class SearchActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_search

    /**
     * 页码
     */
    private var page = 1

    /**
     * 搜索记录
     */
    private var historyList = mutableListOf<String>()

    /**
     * 热门搜索
     */
    private var hotList = mutableListOf<String>()

    /**
     * 搜索关键字
     */
    private var keyWord = ""

    /**
     * 排序方式
     */
    private var sort = ""

    /**
     * 排序参数
     */
    private var rank = ""

    /**
     * 标记是否在搜索页
     */
    private var isSearchPage = true

    /**
     * 标记下拉刷新还是上拉加载
     */
    private var isRefresh = true
    private var content=""
    private var mViewModel: HomeViewModel? = null

    override fun initViews() {
        content=intent.getStringExtra("SearchContent")
        if (content.isNotEmpty()){
            etSearchWord.setText(content)
            etSearchWord.setSelection(content.length)
        }
        ivBack.setOnClickListener {
            onBackPressed()
        }
        tvRightBtn.setOnClickListener {
            searchEditTextContent()
        }
        etSearchWord.setOnEditorActionListener { arg0, arg1, arg2 ->
            if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                searchEditTextContent()
            }
            false
        }
        initRecyclerView()
        initRefreshLayout()
        initClickEvent()
    }

    private fun searchEditTextContent() {
        if (TextUtils.isEmpty(etSearchWord.text)) {
            showToastMsg("搜索内容不能为空")
        } else {
            hideInputBoard(this, etSearchWord)
            keyWord = etSearchWord.text.toString().trim()
            goSearchDetailPage()
        }
    }

    private fun initFlowLayout() {
        mSearchHistory.removeAllViews()
        val inflater = LayoutInflater.from(this)
        for (hot in hotList) {
            val view = inflater.inflate(R.layout.hot_search_item, mSearchHistory, false) as TextView
            view.text = hot
            mSearchHistory.addView(view)
        }
        mSearchHistory.setListener { position, view ->
            keyWord = hotList[position]
            goSearchDetailPage()
        }
        clHotSearch.visibility = View.VISIBLE
    }

    private fun initRecyclerView() {
        val string = AppUtils.getString("searchHistory", "")
        if (string == "") {
            clSearchHistory.visibility = View.GONE
        } else {
            historyList.clear()
            historyList.addAll(Gson().fromJson(string, SearchHistoryBean::class.java).list)
        }
        if (historyList.isEmpty())
            clSearchHistory.visibility = View.GONE
        else
            clSearchHistory.visibility = View.VISIBLE
        val layoutManager = object : androidx.recyclerview.widget.LinearLayoutManager(this) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRecyclerViewHistorySearch.layoutManager = layoutManager
        mRecyclerViewHistorySearch.adapter = HistoryRecordListAdapter(historyList, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                keyWord = arg2 as String
                goSearchDetailPage()
            }
        })
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.adapter = HomeTypeGoodAdapter(arrayListOf(), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                val intent = Intent(this@SearchActivity, GoodDetailActivity::class.java)
                intent.putExtra("good", arg2 as TaobaoGoodBean)
                startActivity(intent)
            }
        })
    }

    private fun goSearchDetailPage() {
        isSearchPage = false
        mScrollView.visibility = View.GONE
        clSearchResultContainer.visibility = View.VISIBLE
        etSearchWord.setText(keyWord)
        etSearchWord.setSelection(keyWord.length)
        if (historyList.contains(keyWord))
            historyList.remove(keyWord)
        historyList.add(0, keyWord)
        if (historyList.isEmpty())
            clSearchHistory.visibility = View.GONE
        else
            clSearchHistory.visibility = View.VISIBLE
        (mRecyclerViewHistorySearch.adapter as HistoryRecordListAdapter).notifyDataSetChanged()
        (mRecyclerView.adapter as HomeTypeGoodAdapter).addData(arrayListOf(PageTipBean("", 0, 0)), 2)
        page = 1
        loadData()
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                loadData()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                page = 1
                loadData()
            }
        })
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        map["pageNo"] = page.toString()
        map["adzoneid"] = if (AppUtils.getString(Contacts.ADZONE_ID, "") == "") Contacts.DEFAULT_ADZONE_ID else AppUtils.getString(Contacts.ADZONE_ID, "")
        map["words"] = keyWord
        if (sort != "" && rank != "") {
            map["sort"] = sort
            map["rank"] = rank
        }
        map["iscoupon"] = "1"
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel?.refreshOptionalSearch(map, true)
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
        if (!mViewModel!!.optionalSearch()!!.hasObservers()) {
            mViewModel!!.getHotKeyword()!!.observe(this, androidx.lifecycle.Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetHotKeyword(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetHotKeyword(hashMapOf(), false)
                        showToastMsg("暂无数据")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetHotKeyword(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null && it.data.data!!.isNotEmpty()) {
                            hotList.clear()
                            hotList.addAll(it.data.data!!)
                            initFlowLayout()
                        } else {
                            println("暂无热搜关键字")
                        }
                    }
                }
            })
            mViewModel!!.optionalSearch()!!.observe(this, androidx.lifecycle.Observer {
                if (it == null) {
                    handleError("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.refreshOptionalSearch(hashMapOf(), false)
                        if (it.error!!.message == "调用出错，请重新尝试")
                            handleError(if (page == 1) "暂无相关商品" else "暂无更多商品")
                        else
                            handleError(parseErrorDate(it.error.message).tip)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.refreshOptionalSearch(hashMapOf(), false)
                        handleError(if (page == 1) "暂无相关商品" else "暂无更多商品")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.refreshOptionalSearch(hashMapOf(), false)
                        handleGoodsContent(it.data!!.data!!.list.result_list.map_data)
                    }
                }
            })
        }
        getHotKeyword()
        if (content.isNotEmpty()){
            searchEditTextContent()
        }
    }

    private fun getHotKeyword() {
        val map = HashMap<String, String>()
        map["num"] = "10"
        mViewModel?.freshGetHotKeyword(map, true)
    }

    private fun handleGoodsContent(list: List<TaobaoGoodBean>) {
        if (page == 1 && isRefresh) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
        if (list.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as HomeTypeGoodAdapter).addData(list, page)
            if (page == 2)
                mRecyclerView.scrollToPosition(0)
        } else {
            handleError(if (page == 1) "暂无相关商品" else "暂无更多商品")
        }
    }

    private fun handleError(msg: String) {
        if (page == 1) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
        if ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] is PageTipBean) {
            ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] as PageTipBean).status = 1
            ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] as PageTipBean).tip = msg
            ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] as PageTipBean).src = R.drawable.ic_data_empty
            (mRecyclerView.adapter as HomeTypeGoodAdapter).notifyItemChanged(0)
        } else showToastMsg(msg)
    }

    private fun initClickEvent() {
        (mViewDataBinding as ActivitySearchBinding).listener = View.OnClickListener {
            when (it.id) {
                R.id.clOrderTotal -> {
                    sort = ""
                    rank = ""
                    tvOrderTotal.setTextColor(ContextCompat.getColor(this, R.color.act_main_bot_nav_select_text_color))
                    tvOrderVolume.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_text_color))
                    tvOrderProfitRatio.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_text_color))
                    ivOrderVolume.setImageResource(R.drawable.ic_order_down)
                    ivOrderProfitRatio.setImageResource(R.drawable.ic_order_down)
                    page = 1
                    loadData()
                }
                R.id.clOrderVolume -> {
                    sort = when {
                        rank != "1" -> "1"
                        sort == "1" -> "2"
                        else -> "1"
                    }
                    rank = "1"
                    tvOrderTotal.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_text_color))
                    tvOrderVolume.setTextColor(ContextCompat.getColor(this, R.color.act_main_bot_nav_select_text_color))
                    tvOrderProfitRatio.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_text_color))
                    if (sort == "1")
                        ivOrderVolume.setImageResource(R.drawable.ic_order_down)
                    else
                        ivOrderVolume.setImageResource(R.drawable.ic_order_up)
                    ivOrderProfitRatio.setImageResource(R.drawable.ic_order_down)
                    page = 1
                    loadData()
                }
                R.id.clOrderProfitRatio -> {
                    sort = when {
                        rank != "2" -> "1"
                        sort == "1" -> "2"
                        else -> "1"
                    }
                    rank = "2"
                    tvOrderTotal.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_text_color))
                    tvOrderVolume.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_text_color))
                    tvOrderProfitRatio.setTextColor(ContextCompat.getColor(this, R.color.act_main_bot_nav_select_text_color))
                    ivOrderVolume.setImageResource(R.drawable.ic_order_down)
                    if (sort == "1")
                        ivOrderProfitRatio.setImageResource(R.drawable.ic_order_down)
                    else
                        ivOrderProfitRatio.setImageResource(R.drawable.ic_order_up)
                    page = 1
                    loadData()
                }
                R.id.ivDeleteSearchRecord -> {
                    showDeleteDialog()
                }
            }
        }
    }

    /**
     * 删除搜索记录确认对话框
     */
    private fun showDeleteDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("提示")
        builder.setMessage("是否清空搜索记录？")
        builder.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
        builder.setPositiveButton("删除") { dialog, _ ->
            historyList.clear()
            clSearchHistory.visibility = View.GONE
            (mRecyclerViewHistorySearch.adapter as HistoryRecordListAdapter).notifyDataSetChanged()
            dialog.dismiss()
        }
        builder.setCancelable(false)
        val dialog = builder.show()
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK)
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK)
    }

    override fun onStop() {
        AppUtils.setString("searchHistory", Gson().toJson(SearchHistoryBean(historyList)))
        super.onStop()
    }

    override fun onBackPressed() {
        if (isSearchPage) finish() else {
            mScrollView.visibility = View.VISIBLE
            clSearchResultContainer.visibility = View.GONE
            isSearchPage = true
        }
    }
}
